package adminUserLoginLogService

import (
	"encoding/json"

	"gitee.com/krio/ginc/example/core/exerr"
	exampleDtoApiPbAdminUserLoginLog "gitee.com/krio/ginc/example/dto/api/pb/admin/user/login_log"
	adminUserLoginLogDao "gitee.com/krio/ginc/example/internal/admin/user/login_log/dao"
	adminUserLoginLogModel "gitee.com/krio/ginc/example/internal/admin/user/login_log/model"
	commonEntry "gitee.com/krio/ginc/example/internal/common/entry/common"
	"github.com/gin-gonic/gin"
)

// AdminUserLoginLogList 列表
func AdminUserLoginLogList(ctx *gin.Context, req *exampleDtoApiPbAdminUserLoginLog.AdminUserLoginLogListReq) (*exampleDtoApiPbAdminUserLoginLog.AdminUserLoginLogListResp, error) {
	resp := &exampleDtoApiPbAdminUserLoginLog.AdminUserLoginLogListResp{}
	search := struct {
		Keyword string `json:"keyword"`
	}{}
	if req.Keywords != "" {
		err := json.Unmarshal([]byte(req.Keywords), &search)
		if err != nil {
			return nil, err
		}
	}
	dao := &adminUserLoginLogDao.AdminUserLoginLogDao{}
	list, total, err := dao.UserLoginLogList(ctx, &commonEntry.ListCommonReq{
		Page:    req.Page,
		Limit:   req.Limit,
		Keyword: search.Keyword,
		OrderBy: []*commonEntry.OrderBy{
			{
				IsDesc: true,
				Field:  "id",
			},
		},
	})
	if err != nil {
		return nil, err
	}
	var data []*exampleDtoApiPbAdminUserLoginLog.AdminUserLoginLogInfo
	for _, v := range list {
		data = append(data, formatDetail(v))
	}
	resp.Total = total
	resp.List = data
	return resp, nil
}

// AdminUserLoginLogDetail 详情
func AdminUserLoginLogDetail(ctx *gin.Context, req *exampleDtoApiPbAdminUserLoginLog.AdminUserLoginLogDetailReq) (*exampleDtoApiPbAdminUserLoginLog.AdminUserLoginLogInfo, error) {
	dao := &adminUserLoginLogDao.AdminUserLoginLogDao{}
	detail, has, err := dao.UserLoginLogDetail(ctx, req.Id)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, exerr.DataNotFound
	}

	return formatDetail(detail), nil
}

// 数据装换
func formatDetail(v *adminUserLoginLogModel.AdminUserLoginLog) *exampleDtoApiPbAdminUserLoginLog.AdminUserLoginLogInfo {
	return &exampleDtoApiPbAdminUserLoginLog.AdminUserLoginLogInfo{
		Id:          v.ID,
		CreateTime:  v.CreatedAt.Format("2006-01-02 15:04:05"),
		UpdateTime:  v.UpdatedAt.Format("2006-01-02 15:04:05"),
		UserId:      v.UserId,
		UserName:    v.UserName,
		UserToken:   v.UserToken,
		LoginIp:     v.LoginIp,
		LoginAgent:  v.LoginAgent,
		LoginResult: v.LoginResult,
	}
}
